<template>
<view class="box">
  <view class="header">
    <scroll-view 
    scroll-with-animation
    enable-back-to-top
    @scroll="scrollTap"
    :scroll-top="scrollTop"
    ref="scrollRef"
    class="msg-box" id="dom" scroll-y>
      <view
      v-for="(item,index) in chatData.msg"
      :key="index"
      class="row-box">
        <view :class="item.status ? 'send-box':'accept-box'">
          <view class="img-box">
            <img  :src="item.status?chatData.img_url:memberStore.userinfo.default_img" alt="" class="img">
          </view>
          <view v-if="item.type==5" class="text">
            <view class="icon"></view>
          <view class="msg">
            {{item.message}}
          </view>
          </view>
          <view v-else class="img-msg">
            <img @click="Preview(item.message)" :src="item.message" alt="" class="img">
          </view>
        </view>
       
      </view>
    
      <view style="height: .2rpx; width: 32.051rpx;"></view>
    </scroll-view>
  </view>
  <view class="feature" :style="{paddingBottom:safeAreaInsets.bottom+'px'}">
    <view class="info" hover-class="btn-hover" @click="selectImg">
      <uni-icons
        type="image"
        size="24"
      />
    </view>
    <input @confirm="sendMessage" confirm-hold comfirm-type="send" v-model="msgInput" type="text"  class="input-msg" />
    <view class="btn" hover-class="btn-hover" @click="sendMessage">发送</view>
  </view>
</view>
</template>

<script setup lang="ts">
import {http} from '@/utlis/http.ts'
import {ref,computed,getCurrentInstance,onMounted,nextTick} from 'vue'
import {onShow,onReady} from '@dcloudio/uni-app'
import {useStore} from 'vuex'
import {useMemberStore} from '@/stores/modules/member.ts'
// import {getFriendListApi} from '@/services/chat'
const scokctType=ref(false)
const scrollTop=ref(0)
const store = useStore()
const scrollTap = (e)=>{
}
const scrollRef=ref("")
onMounted(()=>{
  query.select('.msg-box').fields({size:true,scrollOffset:true},(data) => {
if (data) {
scrollTop.value=Math.ceil(data.scrollHeight-data.height)
}
}).exec();
})
const  {safeAreaInsets}= uni.getSystemInfoSync()
const memberStore = useMemberStore()
const chatData = ref({
  friend_id:1,
  num:0,
  nickname:'张三',
  img_url:'https://www.damer.asia//group1/M00/00/00/CgAICGVKCsWAZzYbAACJ6bxz9-Y7765515.jpg',
  msg:[
    // {
    //   status:1,
    //   type:5,
    //   message:'今天天气真大家开始啦就打开拉萨埃里克的撒开了的撒开了的撒开了的撒开了啊发的时刻了的萨拉好'
    // },
    // {
    //   status:1,
    //   type:5,
    //   message:'我给你发一张照片'
    // },
    // {
    //   status:1,
    //   type:1,
    //   message:'https://cdn.seovx.com/d/?mom=302'
    // },
    // {
    //   status:0,
    //   type:5,
    //   message:'真的好看'
    // },
    // {
    //   status:0,
    //   type:1,
    //   message:'https://cdn.seovx.com/d/?mom=302'
    // },
    // {
    //   status:1,
    //   type:5,
    //   message:'今天天气真好'
    // },
    // {
    //   status:1,
    //   type:5,
    //   message:'我给你发一张照片'
    // },
    // {
    //   status:1,
    //   type:1,
    //   message:'https://cdn.seovx.com/d/?mom=302'
    // },
    // {
    //   status:0,
    //   type:5,
    //   message:'真的好看'
    // },
    // {
    //   status:0,
    //   type:1,
    //   message:'https://cdn.seovx.com/d/?mom=302'
    // },

  ]
})
const msgInput = ref('')
const imgpath = ref('')
const msgnum=computed(()=>{return store.state.msginfo.msgnum})
const urls = computed(()=>{
  return chatData.value.msg.filter(item=>item.type==1).map(item=>item.message)
})
const Preview = (url)=>{
  uni.previewImage({current:url,urls:urls.value})
}
const selectImg = ()=>{
  uni.chooseImage({
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: ({ tempFilePaths, tempFiles }) => {
      imgpath.value=tempFilePaths[0]
      // // #ifdef MP-WEIXIN 
      // // 将图片文件转换为 base64 格式
      // const formData = new FormData();
      // formData.append('file', imgpath.value);
      //   // 发送uni.request请求
      //   uni.request({
      //     url: 'admin/image/', // 上传图片的接口地址
      //     method: 'POST',
      //     header: {
      //       'content-type': 'application/json',
      //     },
      //     data: formData,
      //     success: (requestRes) => {
      //       console.log('上传成功', requestRes);
      //     },
      //     fail: (requestError) => {
      //       console.log('上传失败', requestError);
      //     },
      //   });
      
  
      // // #endif
     // #ifdef H5 || MP-WEIXIN
     uni.uploadFile({
  url: 'https://www.damer.asia/api/admin/image/',
  fileType: 'image',
  filePath: imgpath.value, 
  withCredentials: true,
  name: 'file',
  success: ({ data, statusCode ,head}) => {
    const res = JSON.parse(data)
    console.log(res);
      if(res.code==0){
        chatData.value.msg.push({
          status:0,
          type:1,
          message:'https://www.damer.asia/'+res.url
        })
        
uni.sendSocketMessage({
  data: JSON.stringify({
    friend_id:chatData.value.friend_id,
          status:0,
          type:1,
          message:'https://www.damer.asia/'+res.url
        }),
  success: (result) => {
    console.log('success',result);
  },
  fail: (error) => {}
})
      }
      else{
        uni.showToast({
          title:'发送失败'

        })
      }
  },
  fail: (error) => {}
})
     // #endif
    },
    fail: (error) => {
      uni.showToast({
        title: '授权失败',
        icon: 'error',
        mask: true
      })
    }
  
  })
  
}


const instance = getCurrentInstance();

const query = uni.createSelectorQuery().in(instance);

const Initialization =async ()=>{
// console.log([1,2].constructor==Array);
store.commit('clearMsgNum',0)
if(chatData.value.msg.length ==0){
  uni.request({
  url: 'friend/list/',
  header: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  },
  method: 'GET',
  sslVerify: true,
  success: ({ data, statusCode, header }) => {
    console.log(data);
    if(data.code==200){
      // chatData.value={...data.data[0],msg:[]}
      chatData.value.friend_id=data.data[0].friend_id
      chatData.value.nickname=data.data[0].nickname,
      chatData.value.img_url.data.data[0].img_url
    }
  },
  fail: (error) => {}
})

}
}
Initialization()
const sendMessage =async ()=>{
if(!msgInput.value)return;
if(!scokctType.value)uni.connectSocket({
	url: 'wss://www.damer.asia/chat/',
	method: 'GET',
  header:{withCredentials:true},
  complete:(res)=>{console.log(res);}
});
chatData.value.msg.push({
  status:0,
  type:5,
  message:msgInput.value
})
await nextTick()
query.select('.msg-box').fields({size:true,scrollOffset:true},(data) => {
if (data) {
scrollTop.value=Math.ceil(data.scrollHeight-data.height-1)
console.log(scrollTop.value)
}
}).exec();

uni.sendSocketMessage({
  data: JSON.stringify({
    friend_id:chatData.value.friend_id,
  type:5,
  message:msgInput.value
}),
  success: (result) => {
    console.log('success',result);
  },
  fail: (error) => {}
})
msgInput.value=''

}
const  socketTask= uni.connectSocket({
	url: 'wss://www.damer.asia/chat/',
	method: 'GET',
  header:{withCredentials:true},
  complete:(res)=>{console.log(res);}
});
uni.onSocketOpen((result) => {
  
  console.log('已连接',result);
  scokctType.value=true
})
uni.onSocketClose((result) => {
  console.log('close',result);
})
uni.onSocketMessage(async({ data }) => {
  data=JSON.parse(data)
  console.log('accept',data);
  console.log(chatData.value);
  if(data.constructor == Array){
  
  data.map(item=>{chatData.value.msg.push({...item,status:1});store.commit('setMsgNum',1)})

  }
  else{
    chatData.value.msg.push({...data,status:1})
    store.commit('setMsgNum',1)
  }
  await nextTick()
query.select('.msg-box').fields({size:true,scrollOffset:true},(data) => {
if (data) {
scrollTop.value=Math.ceil(data.scrollHeight-data.height-1)
console.log(scrollTop.value)
}
}).exec();
})
uni.onSocketError((result) => {
  console.log('err',result);
})

</script>

<style lang="scss">
  page{
    overflow: hidden;
  background-color: #ededed;

  }
.box{

  display: flex;
  /* #ifdef H5 */
  height: calc(100vh - 44px);
  /* #endif */
  /* #ifdef MP-WEIXIN */
  height: calc(100vh);
  /* #endif */
  flex-direction: column;
  .header{
    flex-grow: 1;
    padding: 0 22.436rpx;
    background-color: #ededed;
  overflow: hidden;
  ::-webkit-scrollbar{
    display: none;
    width: 0;
  }

    .msg-box{
      height: 100%;
      flex: 1;
      overflow:auto;
      margin-bottom: 32.051rpx;
      .row-box{
        margin-bottom: 32.051rpx;
        .send-box{
          display: flex;
          .img-box{
            width: 80.128rpx;
            height: 80.128rpx;
            min-width: 80.128rpx;
            min-height: 80.128rpx;
            overflow: hidden;
            border-radius: 3.205rpx;
            .img{
              height: 100%;
              width: 100%;
            object-fit: cover;

            }
          }
         .text{
          display: flex;
          .icon{
            position: relative;
            height: 80.128rpx;
            width: 25.641rpx;
            min-width: 25.641rpx;
            &::after{
              position: absolute;
              content: ' ';
              top:50%;
              width: 0px;
              height: 0px;
              border-top: 12.821rpx solid rgba(0,0,0,0);
              border-left:  12.821rpx solid rgba(0,0,0,0);
              border-bottom:  12.821rpx solid rgba(0,0,0,0);
              border-right: 13.921rpx solid #fff;
              transform: translateY(-12.821rpx);

            }
          }
          .msg{
            max-width: 512.821rpx;
              padding: 19.231rpx;
              color: 32.051rpx;
              font-size: 32.051rpx;
              border-radius: 6.41rpx;
              background-color: #fff;
          }
         }
         
        }
        .img-msg{
          min-width: 180rpx;
          min-height: 180rpx;
          height: 269.231rpx;
          width: 269.231rpx;
          max-width: 350rpx;
          max-height: 350rpx;
          margin:0 25.641rpx;
          border-radius: 6.41rpx;
          overflow: hidden;
          .img{
            width: 100%;
            height: 100%;
            object-fit: cover;
            /* background-color: red; */
          }
         }
        .accept-box{
          display: flex;
          flex-direction:  row-reverse;
          .img-box{
            width: 80.128rpx;
            height: 80.128rpx;
            min-width: 80.128rpx;
            min-height: 80.128rpx;
            overflow: hidden;
            border-radius: 3.205rpx;
            .img{
              height: 100%;
              width: 100%;
            object-fit: cover;

            }
          }
          .text{
            display: flex;
            flex-direction: row-reverse;
            .icon{
            position: relative;
            height: 80.128rpx;
            width: 25.641rpx;
            &::after{
              position: absolute;
              content: ' ';
              top:50%;
              width: 0px;
              height: 0px;
              border-top: 12.821rpx solid rgba(0,0,0,0);
              border-right:  12.821rpx solid rgba(0,0,0,0);
              border-bottom:  12.821rpx solid rgba(0,0,0,0);
              border-left: 12.821rpx solid #95ec69;
              transform: translateY(-12.821rpx);

            }
          }
          .msg{
              max-width: 487.179rpx;
              padding: 19.231rpx;
              color: 32.051rpx;
              font-size: 32.051rpx;
              border-radius: 6.41rpx;
              background-color: #95ec69;

          }
          }
        }
      }
      .row-box:nth-child(1){
        margin-top: 32.051rpx;
      }
    }
  }
  .feature{
    position: sticky;
    bottom: 0;
    display: flex;
    width: 100%;
    min-height: 96.154rpx;
    align-items: center;
    justify-content: space-between;
    font-size: 32.051rpx;
    background-color: #f6f6f6;
    transition: .05s;
    .info{
      margin: 0 19.231rpx;
    }

    .input-msg{
      flex-grow: 1;
      height: 73.718rpx;
      padding: 0 3.205rpx;
      border-radius: 6.41rpx;
      background-color: #fff;
    }
    .btn{
      width: 128.205rpx;
      height: 64.103rpx;
      margin: 0 19.231rpx;
      line-height: 64.103rpx;
      color: #fff;
      text-align: center;
      border-radius: 12.821rpx;
      background-color: #6ff02f;
    }
    .btn-hover{
      transform-origin: center;
      opacity: .8;
      transform: scale(98%);
    }
  }

}
</style>